@page
@using Microsoft.AspNetCore.Authentication
@using System.Security.Claims
<!DOCTYPE html>
<html>
<head>
    <title>Authentication</title>
</head>
<body>
    <h1 id="authentication">Authentication</h1>
    <p>
        This is a completely fake login mechanism for automated test purposes.
        It accepts any username, with no password.
    </p>
    <p>
        <strong>Obviously you should not do this in real applications.</strong>
        See also: <a href="https://docs.microsoft.com/aspnet/core/security">documentation on configuring a real login system.</a>
    </p>

    <fieldset>
        <h3>Sign in</h3>

        @* Do not use method="get" for real login forms. This is just to simplify E2E tests. *@
        <form method="get">
            <p>
                User name:
                <input name="username" />
            </p>
            <p>
                Roles:
                <input name="roles" />
            </p>
            <p>
                <button type="submit">Submit</button>
            </p>
        </form>
    </fieldset>

    <fieldset>
        <h3>Status</h3>
        <p>
            Authenticated: <strong>@User.Identity.IsAuthenticated</strong>
            Username: <strong>@User.Identity.Name</strong>
            Roles:
            <strong>
                @string.Join(", ", User.Claims.Where(c => c.Type == ClaimTypes.Role).Select(c => c.Value).ToArray())
            </strong>
        </p>foreach
        <a href="Authentication?signout=true">Sign out</a>
    </fieldset>
</body>
</html>

@functions {
    public async Task<IActionResult> OnGet()
    {
        if (Request.Query["signout"] == "true")
        {
            await HttpContext.SignOutAsync();
            return Redirect("Authentication");
        }

        var username = Request.Query["username"];
        if (!string.IsNullOrEmpty(username))
        {
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, username),
                new Claim("test-claim", "Test claim value"),
            };

            var roles = Request.Query["roles"];
            if (!string.IsNullOrEmpty(roles))
            {
                foreach (var role in roles.ToString().Split(','))
                {
                    claims.Add(new Claim(ClaimTypes.Role, role));
                }
            }

            await HttpContext.SignInAsync(
                new ClaimsPrincipal(new ClaimsIdentity(claims, "FakeAuthenticationType")));

            return Redirect("Authentication");
        }

        return Page();
    }
}
